package com.iyundao.io.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iyundao.io.Service.SysMenuService;
import com.iyundao.io.mapper.SysMenuSqlMapper;
import com.iyundao.io.mapper.SysRoleSqlMapper;
import com.iyundao.io.model.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by black on 2019/4/24.
 */
@Service("sysMenuService")
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuSqlMapper sysMenuSqlMapper;

    @Autowired
    private SysRoleSqlMapper sysRoleSqlMapper;

    @Override
    public List<SysMenuProvider> getMenuByRoleId() {
        SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
        SysRole role = sysRoleSqlMapper.selectByUserId(sysUser.getSid());
        List<SysMenuProvider> outList = getMenu(role.getSid(),"0");
        return outList;
    }

    List<SysMenuProvider> getMenu(String rid, String parentId){
        Map tempRoleMap = new HashMap();
        tempRoleMap.put("rid",rid);
        tempRoleMap.put("parentId",parentId);
        List<SysMenu> menuList = sysMenuSqlMapper.selectMenuByRoleId(tempRoleMap);
        List<SysMenuProvider> menuAndChildList = new ArrayList<>();
        for(SysMenu sysMenu : menuList){
            String jsonString = JSONObject.toJSONString(sysMenu);
            SysMenuProvider tempMenuProvider = JSONObject.toJavaObject(JSONObject.parseObject(jsonString), SysMenuProvider.class);
            tempMenuProvider.setChild(getMenu(rid,sysMenu.getSid()));
            menuAndChildList.add(tempMenuProvider);
        }
        return menuAndChildList;
    }
}
